<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\Request;
use App\Http\model\Purchcar;
use App\Http\model\Curdpost;
use App\Http\Comm\CommonController as common;

class PurchcarController extends Controller
{
	/*
    |--------------------------------------------------------------------------
    |限号处理部分
    |--------------------------------------------------------------------------
    */
   /**
    * [limitNumber 添加限号规则]
    * @Author   孙丽男
    * @DateTime 2018-06-07
    * @param [限号规则] 二维数组 $rule;
    * @version  6.2]
    * @return   [json]     [$result]
    */
	public function addNumber(Request $request){

		$result = array();

		if ($request['area'] && $request['scope']&&$request['start_time'] && $request['end_time']&& $request['rule']) {
			
			$data = $request->all();
            if (isset($data['s'])) {
                $data = array_except($data, ['s']);
            }
			$data['rule'] = json_encode($data['rule']);
			$purchar = new Purchcar;
			$result = $purchar->addNumberModel($data);

			return $result;
		}else{

			$result['code'] = 1002;
    		$result['msg'] = '参数为空';
    		return json_encode($result);
		}
	}

	/**
	 * [findNumber 限号列表]
	 * @Author   孙丽男
	 * @DateTime 2018-06-07
	 * @version  6.2
	 * @return   [type]     [description]
	 */
	public function findNumber(Request $request){
  
		//构建查询条件
        $where = array();

         if ($request['numberId']) {
            
            $where = [
                ['scope.id', $request['numberId']],
            ]; 
        }

        if ($request['area']) {
            
            $where[1] = ['scope.area',  $request['area'] ];
        }
        $purchar = new Purchcar;

        $result = $purchar->findNumberModel($where);

        return $result;
	}

	/**
	 * [deleteNumber 删除限号]
	 * @Author   孙丽男
	 * @DateTime 2018-06-07
	 * @param    [限号id] arr $numberId[]
	 * @version  6.2
	 * @return   [json]      [$result]
	 */
	public function deleteNumber(Request $request){

		$result = array();
   
        if (is_array($request['numberId'])) {

            $numberIdArr = $request->get('numberId');

			$purchar = new Purchcar;
            $result = $purchar->deleteNumberModel($numberIdArr);

            return $result;

        }else{

            $result['code'] = 1002;
            $result['msg'] = '参数为空';
            return json_encode($result);
        }


	}
	/**
	 * [updateNumber 修改限号]
	 * @Author   孙丽男
	 * @DateTime 2018-06-08
	 * @param    [type]
	 * @version  6.2
	 * @param    Request    $request [description]
	 * @return   [type]              [description]
	 */
	public function updateNumber(Request $request){
		$result = array();

		if ($request['area'] && $request['scope']&&$request['start_time'] && $request['end_time']&& $request['rule']&& $request['numberId']) {
			
			$data = $request->all();
            if (isset($data['s'])) {
                $data = array_except($data, ['s']);
            }
			$data['rule'] = json_encode($data['rule']);
            $numberId = $data['numberId'];
            unset($data['numberId']);
			$purchar = new Purchcar;
			$result = $purchar->updateNumberModel($data,$numberId);

			return $result;
		}else{

			$result['code'] = 1002;
    		$result['msg'] = '参数为空';
    		return json_encode($result);
		}
	}
	/*
    |--------------------------------------------------------------------------
    |厂商部分
    |--------------------------------------------------------------------------
    */
   /**
    * [addSupp 增加厂商]
    * @Author   孙丽男
    * @DateTime 2018-06-07
    * @version  6.2
    */
    public function addSupp(Request $request){

		$result = array();

		if ($request['name'] ) {

			$data['name'] = $request['name'];
			$purchar = new Purchcar;
			$result = $purchar->addSuppModel($data);

			return $result;
		}else{

			$result['code'] = 1002;
			$result['msg'] = '参数为空';
			return json_encode($result);
		}
    }

    /**
     * [findSupp 厂商列表]
     * @Author   孙丽男
     * @DateTime 2018-06-07
     * @version  6.2
     * @return   [type]              [description]
     */
    public function findSupp(Request $request){

    	//构建查询条件
        $where = array();

        if ($request['suppId']) {
            
            $where = [
                ['supplier.id', $request['suppId']],
            ]; 
        }

       if ($request['start_time']) {
            
            $where[2] =  ['supplier.create_time', '>',  $request['start_time']];
        }

        if ($request['end_time']) {
            
            $where[3] =  ['supplier.create_time', '<',  $request['end_time']];
        }


		$purchar = new Purchcar;
		$result = $purchar->findSuppModel($where);

		return $result;
    }

    /**
     * [deleteSupp 删除厂商]
     * @Author   孙丽男
     * @DateTime 2018-06-07
     * @param    [厂商id] arr $suppId[]
     * @version  6.2
     * @return   [json]     [$result]
     */
    public function deleteSupp(Request $request){
    	$result = array();
   
        if (is_array($request['suppId'])) {

            $suppIdArr = $request->get('suppId');

			$purchar = new Purchcar;
            $result = $purchar->deleteSuppModel($suppIdArr);

            return $result;

        }else{

            $result['code'] = 1002;
            $result['msg'] = '参数为空';
            return json_encode($result);
        }

    }

    /**
     * [updateSupp 修改厂商]
     * @Author   孙丽男
     * @DateTime 2018-06-08
     * @param    [type]
     * @version  6.2
     * @return   [type]     [description]
     */
    public function updateSupp(Request $request){

		$result = array();

		if ($request['name'] && $request['suppId']) {

			$data['name'] = $request['name'];
			$purchar = new Purchcar;
			$result = $purchar->updateSuppModel($data, $request['suppId']);

			return $result;
		}else{

			$result['code'] = 1002;
			$result['msg'] = '参数为空';
			return json_encode($result);
		}
    }
    /*
    |--------------------------------------------------------------------------
    |采购处理部分
    |--------------------------------------------------------------------------
    */
   
   /**
    * [addPurch 增加采购商]
    * @Author   孙丽男
    * @DateTime 2018-06-07
    * @version  6.2
    */
   public function addPurch(Request $request){

   		$result = array();

   		if ($request['car_id'] && $request['number'] && $request['price'] && $request['time'] && $request['supp_id']) {
   			
   			$data = $request->all();
            if (isset($data['s'])) {
                $data = array_except($data, ['s']);
            }

   			$purchar = new Purchcar;
            $result = $purchar->addPurchModel($data);

            return $result;

   		}else{

            $result['code'] = 1002;
            $result['msg'] = '参数为空';
            return json_encode($result);
        }
   }

   /**
    * [findPurch 采购列表]
    * @Author   孙丽男
    * @DateTime 2018-06-08
    * @param    [厂商id] int $suppId
    * @version  6.2
    * @return   [type]     [description]
    */
    public function findPurch(Request $request){

   		$result = array();
   		if ($request['suppId'] || $request['purchId']) {
            $where = array();
            if ($request['purchId']) {

                $where[0] =  ['purchase.id', $request['purchId']];
            }
            if ($request['suppId']) {

                $where[0] =  ['purchase.supp_id',  $request['suppId']];
            }

            $purchar = new Purchcar;
			$result = $purchar->findPurchModel($where);

			return $result;

         }else{
         	$result['code'] = 1002;
            $result['msg'] = '参数为空';
            return json_encode($result);
         }	
    }

    /**
     * [updatePurch 修改采购]
     * @Author   孙丽男
     * @DateTime 2018-06-08
     * @param    [type]
     * @version  6.2
     * @param    Request    $request [description]
     * @return   [type]              [description]
     */
    public function updatePurch(Request $request){

   		$result = array();

   		if ($request['car_id'] && $request['number'] && $request['price'] && $request['time'] && $request['supp_id']&&$request['purchId']) {
   			
   			$data = $request->all();
            if (isset($data['s'])) {
                $data = array_except($data, ['s']);
            }
            unset($data['purchId']);
   			$purchar = new Purchcar;
            $result = $purchar->updatePurchModel($data,$request['purchId']);

            return $result;

   		}else{

            $result['code'] = 1002;
            $result['msg'] = '参数为空';
            return json_encode($result);
        }
   }

    /*
    |--------------------------------------------------------------------------
    |平台车辆处理部分
    |--------------------------------------------------------------------------
    */
   /**
    * [addCar 添加平台车辆]
    * @Author   孙丽男
    * @DateTime 2018-06-08
    * @param    [type]
    * @version  6.2
    */
    public function addCar(Request $request){

	 	$car = $request['car'];
        $insura = $request['insurance'];
        $insura['num'] = $car['num'];
	 	$purchar = new Purchcar;
		$result = $purchar->addCarModel($car,$insura);
        //判断是否添加成功，添加成功同步，不成功直接返回
        if ($result['code'] != 1000) {
            
            return json_encode($result);
        }else{
            //同步数据
            $res = $this->syncData($car,1);
            $res2 = $this->syncInsura($insura,1);
            if (!$res) {
                $result['code'] = 1004;
                $result['msg'] = '司机同步失败';
                return json_encode($result);
            }
            if (!$res2) {
                $result['code'] = 1004;
                $result['msg'] = '保险同步失败';
                return json_encode($result);
            }
            $result['code'] = 1000;
            $result['msg'] = '同步成功';
            return json_encode($result);
        }
       
    }

    /**
     * [findCar 平台车辆列表]
     * @Author   孙丽男
     * @DateTime 2018-06-08
     * @param    [type]
     * @version  6.2
     * @return   [type]     [description]
     */
    public function findCar(Request $request){

    	$where = array();
        if ($request['carId']) {

            $where[0] =  ['car_car.id', '=',  $request['id']];
        }
    	if ($request['start_time']) {
            
            $where[1] =  ['car_car.modtime', '>',  $request['start_time']];
        }

        if ($request['end_time']) {
            
            $where[2] =  ['car_car.modtime', '<',  $request['end_time']];
        }

        $purchar = new Purchcar;
		$result = $purchar->findCarModel($where);

		return $result;

    }
    /**
     * [deleteCar 删除平台车辆]
     * @Author   孙丽男
     * @DateTime 2018-06-08
     * @param    [车辆id] arr $carId[]
     * @version  6.2
     * @return   [type]     [description]
     */
    public function deleteCar(Request $request){

    	$result = array();
   
        if (is_array($request['carId'])) {

            $carIdArr = $request->get('carId');

			$purchar = new Purchcar;
            $result = $purchar->deleteCarModel($carIdArr);

             //判断是否成功，成功同步，不成功直接返回
            if ($result['code'] != 1000) {
                
                return json_encode($result);
            }else{
                //同步数据
                $res = $this->syncData($result['num'],3);
                $res2 = $this->syncInsura($result['num'],3);
                if (!$res) {
                    $result['code'] = 1004;
                    $result['msg'] = '司机同步失败';
                    return json_encode($result);
                }
                if (!$res2) {
                    $result['code'] = 1004;
                    $result['msg'] = '保险同步失败';
                    return json_encode($result);
                }
                $result['code'] = 1000;
                $result['msg'] = '同步成功';
                return json_encode($result);
            }

        }else{

            $result['code'] = 1002;
            $result['msg'] = '参数为空';
            return json_encode($result);
        }
    }

    /**
     * [updateCar 修改平台车辆]
     * @Author   孙丽男
     * @DateTime 2018-06-08
     * @param    [type]
     * @version  6.2
     * @return   [type]     [description]
     */
    public function updateCar(Request $request){

	 	$car = $request['car'];
        $insura = $request['insurance'];
        $insura['num'] = $car['num'];
        $carId = $car['carId'];
        unset($car['carId']);
        $purchar = new Purchcar;
        foreach ($insura as $key => $value) {

            //判断是添加还是修改
            if (empty($value['id'])) {
                $value['carid'] = $carId;
                $addData[] = $insura[$key];
                unset($insura[$key]);
            }
        }
        $result = $purchar->updateCarModel($car,$carId,$insura,$addData);
        //判断是否成功，成功同步，不成功直接返回
        if ($result['code'] != 1000) {
            
            return json_encode($result);
        }else{
            //同步数据
            $res = $this->syncData($car,2);
            $res2 = $this->syncInsura($insura,2);
            if (!$res) {
                $result['code'] = 1004;
                $result['msg'] = '司机同步失败';
                return json_encode($result);
            }
            if (!$res2) {
                $result['code'] = 1004;
                $result['msg'] = '保险同步失败';
                return json_encode($result);
            }
            $result['code'] = 1000;
            $result['msg'] = '同步成功';
            return json_encode($result);
        }
    }
    /**
     * [deleteInsura 删除保险]
     * @Author   孙丽男
     * @DateTime 2018-06-21
     * @param    [type]
     * @version  6.2
     * @return   [type]     [description]
     */
    public function deleteInsura(Request $request){
        if ($request['id']) {
            $purchar = new Purchcar;
    
            $result = $purchar->deleteInsuraModel($request['id']);
            //判断是否成功，成功同步，不成功直接返回
            if ($result['code'] != 1000) {
                
                return json_encode($result);
            }else{
                //同步数据
                $res = $this->syncInsura($result['num'],3);
                if (!$res) {
                    $result['code'] = 1004;
                    $result['msg'] = '同步失败';
                    return json_encode($result);
                }
                
                $result['code'] = 1000;
                $result['msg'] = '同步成功';
                return json_encode($result);
            }
        }else{
            $result['code'] = 1002;
            $result['msg'] = '参数为空';
            return json_encode($result);

        }
        
    }
    /**
     * [syncData 平台车辆数据同步]
     * @Author   孙丽男
     * @DateTime 2018-06-20
     * @param    [type]
     * @version  6.2
     * @return   [type]     [description]
     */
   
    private function syncData($data,$flag){

        $result = array();
        $curd = new Curdpost;
        //判断是CURD的哪一个操作
        if ($flag == 1) {
            $purch = new Purchcar;
            $findSync = $purch->findSync($data['typeid']);
            $wyc = $this->syncFileds('vehicle',$data,$findSync);
            $wyc['CertifyDateB'] = date('YmdHis',time());//'车辆初次登记日期（YYYYMMDD）（必填）（注册日期）';
            $wyc['Flag'] = $flag;//'操作标识 （1：新增 2：更新 3：删除）';
            $res = $curd->NewInsert('vehicle',$wyc);
            if ($res) {
                $result = false;
            }else{
                $result = true;
            }

        }elseif($flag == 2){
            $findSync = $purch->findSync($data['typeid']);
            $wyc['Flag'] = $flag;//'操作标识 （1：新增 2：更新 3：删除）';
            $wyc = $this->syncFileds('vehicle',$data,$findSync);
            $where = "VehicleNo=".'"'.$data['num'].'"';
            $res = $curd->NewUpdate($wyc,$where);
           if ($res) {
                $result = false;
            }else{
                $result = true;
            }
        }elseif($flag == 3){
            $where = "VehicleNo in (";
            foreach ($data as $key => $value) {
                $where .= '"'.$value['num'].'",';
            }
            $where = substr($where,0,strlen($where)-1); 
            $where .= ')';
            $res = $curd->NewDel('vehicle',$where);
           if ($res) {
                $result = false;
            }else{
                $result = true;
            }
        }
        return $result;

    }
    /**
     * [syncFileds 整理同步车辆基本信息字段]
     * @Author   孙丽男
     * @DateTime 2018-06-21
     * @param    [type]
     * @version  6.2
     * @param    [type]     $data [description]
     * @return   [type]           [description]
     */
    private function syncFileds($data,$findSync){

        $wyc['CompanyId'] = '公司标识';
        $wyc['Address'] = $data['area'];//'车辆所在城市（注册地行政区代码）';
        $wyc['VehicleNo'] =  $data['num'];//'车牌号';
        $wyc['PlateColor'] = 1;//'车牌颜色';
        $wyc['Seats'] = $findSync['maxride'];//'载客位';
        $wyc['Brand'] = $findSync['brandname'];//'车辆厂牌';
        $wyc['Model'] = $findSync['typename'];//'车辆型号';
        $wyc['VehicleType'] = $findSync['levelname'];//'车辆类型（以机动车行驶证为准）';
        $wyc['OwnerName'] = $data['owner'];//'车辆所有人（应与《机动车登记证书》所注明的车辆所有人一致）';
        $wyc['VehicleColor'] = $data['color'];//'车身颜色';
        $wyc['EngineId'] = $data['enginenum'];//'发动机号（以机动车行驶证为准）';
        $wyc['VIN'] = $data['Vin'] ;//'VIN';
        $wyc['CertifyDateA'] = $data['regdate'] ;//'车辆注册日期（以机动车行驶证为准）';
        $wyc['FuelType'] = $findSync['energy'];//'车辆燃料类型';
        $wyc['EngineDisplace'] = $findSync['displacement'];//'发动机排量';
        $wyc['PhotoId'] = '';
        $wyc['Certificate'] = $data['cardnum'] ;//'运输证字号';
        $wyc['TransAgency'] = $data['outfit'] ;//'车辆运输证发证机构';
        $wyc['TransArea'] = 110000;//'车辆经营区域（必填）';
        $wyc['TransDateStart'] = $data['startdate'] ;//'车辆运输证有效期起（YYYYMMDD）';
        $wyc['TransDateStop'] = $data['enddata'] ;//'车辆运输证有效期止（YYYYMMDD）';
        $wyc['FixState'] = $data['overhastatus'] ;//'车辆检修状态 数据取值有效范围： 0：未检修 1：已检修 2：未知';
        $wyc['NextFixDate'] = $data['nextdue'];//'车辆下次年检时间';
        $wyc['CheckState'] = $data['due'];//'车辆年度审验状态（必填   年检？）';
        $wyc['FeePrintId'] = $data['printnum'];//'发票打印设备序列号';
        $wyc['GPSBrand'] = $data['gpsbrand'];//'卫星定位装置品牌';
        $wyc['GPSModel'] = $data['gpsmodel'];//'卫星定位装置型号';
        $wyc['GPSIMEI'] = $data['gpsimei'] ;//'卫星定位装置IMEI号';
        $wyc['GPSInstallDate'] = $data['gpsdate'] ;//'卫星定位设备安装日期 （YYYYMMDD）';
        $wyc['RegisterDate'] = $data['prepdate'] ;//'报备日期 （车辆信息向服务所在地出租汽车行政主管部门报备日期 YYYYMMDD';
        $wyc['Commercial-Type'] = 1;//'服务类型 （1：网络预约出租车汽车 2：巡游出租汽车 3：私人小客车合成';
        $wyc['FareType'] = 1;//'运价类型编码 （有网约车公司定义，与A4.5运价信息接口一一对应）';
        $wyc['State'] = 0;//'状态 0：有效 1：失效';
        $wyc['UpdateTime'] = $data['modtime'] ;//'更新时间 （网约车平台完成数据更新的时间 YYYYMMDDhhmmss）';
        return $wyc;
    }
    /**
     * [syncInsura 同步保险信息]
     * @Author   孙丽男
     * @DateTime 2018-06-21
     * @param    [type]
     * @version  6.2
     * @return   [type]     [description]
     */
    public function syncInsura($insura,$flag){
        $result = array();
        $curd = new Curdpost;
        if ($flag == 1) {
            $data['CompanyId'] = '公司标识';
            $data['VehicleNo'] = $insura['num'];//车辆号牌
            $data['InsurCom'] = $insura['company'];//保险公司名称
            $data['InsurNum'] = $insura['number'];//保险号
            $data['InsurType'] = $insura['type'];//保险类型
            $data['InsurCount'] = $insura['money'];//保险金额
            $data['InsurEff'] = data('Ymd',strtotime($insura['startdate']));//保险生效时间（YYYYMMDD）
            $data['InsurExp'] = date('Ymd',strtotime($insura['enddate']));//保险到期时间（YYYYMMDD）
            $data['Flag'] = $flag;//操作标识 1：新增 2：更新 3：删除
            $data['UpdateTime'] = date('YmdHis',time());
            $res = $curd->NewInsert('vehicleinsurance',$data);
            if ($res) {
                $result = false;
            }else{
                $result = true;
            }
        }elseif ($flag == 2) {
            $data['CompanyId'] = '公司标识';
            $data['VehicleNo'] = $insura['num'];//车辆号牌
            $data['InsurCom'] = $insura['company'];//保险公司名称
            $data['InsurNum'] = $insura['number'];//保险号
            $data['InsurType'] = $insura['type'];//保险类型
            $data['InsurCount'] = $insura['money'];//保险金额
            $data['InsurEff'] = data('Ymd',strtotime($insura['startdate']));//保险生效时间（YYYYMMDD）
            $data['InsurExp'] = date('Ymd',strtotime($insura['enddate']));//保险到期时间（YYYYMMDD）
            $data['Flag'] = $flag;//操作标识 1：新增 2：更新 3：删除
            $data['UpdateTime'] = date('YmdHis',time());
            $where = "VehicleNo=".'"'.$insura['num'].'"';
            $res = $curd->NewUpdate('vehicleinsurance',$data,$where);
            if ($res) {
                $result = false;
            }else{
                $result = true;
            }
        }elseif ($flag == 3) {
            $where = "VehicleNo in (";
            foreach ($insura as $key => $value) {
                $where .= '"'.$value['num'].'",';
            }
            $where = substr($where,0,strlen($where)-1); 
            $where .= ')';
            $res = $curd->NewDel('vehicleinsurance',$where);
           if ($res) {
                $result = false;
            }else{
                $result = true;
            }
        }

        return $result;
    }
    /*
    |--------------------------------------------------------------------------
    |添加、修改下拉选项数据展示部分
    |--------------------------------------------------------------------------
    */
   
    /**
    * [purchbrand 已采购车辆品牌]
    * @Author   孙丽男
    * @DateTime 2018-06-08
    * @param    [type]
    * @version  6.2
    * @return   [type]     [description]
    */
   public function purchBrand(){

        $purchar = new Purchcar;
        $result = $purchar->purchBrandModel();

        return $result;
   }

   /**
    * [purchbrand 已采购车辆子品牌]
    * @Author   孙丽男
    * @DateTime 2018-06-08
    * @param    [type]
    * @version  6.2
    * @return   [type]     [description]
    */
   public function purchChild(Request $request){

   		if (!$request['pid']) {

   			$result['code'] = 1002;
            $result['msg'] = '参数为空';
            return json_encode($result);
   		}
        $pid = $request['pid'];
   		$purchar = new Purchcar;
		$result = $purchar->purchChildModel($pid);

		return $result;
   }

   /**
    * [purchbrand 已采购车系]
    * @Author   孙丽男
    * @DateTime 2018-06-08
    * @param    [type]
    * @version  6.2
    * @return   [type]     [description]
    */
   public function purchSeries(Request $request){

   		if ($request['brandId']) {

   			$purchar = new Purchcar;
			$result = $purchar->purchseriesModel($request['brandId']);

			return $result;
   			
   		}else{

   			$result['code'] = 1002;
            $result['msg'] = '参数为空';
            return json_encode($result);
   		}
   }

   /**
    * [purchbrand 已采购车辆车型]
    * @Author   孙丽男
    * @DateTime 2018-06-08
    * @param    [type]
    * @version  6.2
    * @return   [type]     [description]
    */
   public function purchType(Request $request){

   		if ($request['seriesId']) {

   			$purchar = new Purchcar;
			$result = $purchar->purchTypeModel($request['seriesId']);

			return $result;
   			
   		}else{

   			$result['code'] = 1002;
            $result['msg'] = '参数为空';
            return json_encode($result);
   		}
        
   }


   /**
    * [purchbrand 所属公司]
    * @Author   孙丽男
    * @DateTime 2018-06-08
    * @param    [type]
    * @version  6.2
    * @return   [type]     [description]
    */
   public function company(Request $request){

		$purchar = new Purchcar;
		$result = $purchar->companyModel();

		return $result;
   }
   /**
    * [area 地区列表]
    * @Author   孙丽男
    * @DateTime 2018-06-12
    * @param    [type]
    * @version  6.2
    * @return   [type]     [description]
    */
   public function area(Request $request){

        $purchar = new Purchcar;
        $result = $purchar->areaModel();

        return $result;
   }
}